<template>
  <div>
    <p>
      <a-button @click="saveIframeImg">saveIframeImg</a-button>
      <a-button @click="download">back</a-button>
      <a-button @click="download">download</a-button>
      <a-button @click="post">post</a-button>
      <a-button @click="gotoDownload">goto download</a-button>
    </p>
    <div ref="framediv" style="height:0px;width:500px">
      <iframe
        ref="frame"
        frameborder="0"
        height="100%"
        width="100%"
        src="/htmlempty"
        @load="frameload"
      ></iframe>
    </div>
    <img src="" ref="img" alt="" />
  </div>
</template>

<script lang="renderjs">
import html2canvas from "html2canvas";
import { downloadFileFromBlobUrl } from "@/utils/downloader";
export default {
  data() {
    return {
      html: `
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
    <h1 style='color:red'>test</h1>
</body>
</html>`,
      posterUrl: "",
    };
  },
  mounted() {
    // this.$nextTick(() => {
    //   this.$refs.frame.srcdoc = this.html;
    // });
  },
  methods: {
    gotoDownload()
    {
      //在起始页面跳转到test.vue页面并传递参数
      uni.navigateTo({
        url: '/pages/webview/download?data='+encodeURIComponent(this.posterUrl)
      });
    },
    async frameload() {
      //获取所有的图片路径，通过自己 的服务下载 图片base64数据，并替换原路径
      let document = this.$refs.frame.contentWindow.document;
      document.getElementsByTagName("body")[0].innerHTML = this.html;
      this.saveIframeImg();
    },
    saveIframeImg() {
      let document = this.$refs.frame.contentWindow.document;
      this.saveImg(document.getElementsByTagName("body")[0]);
    },

    saveImg(el) {
      html2canvas(el, {
        backgroundColor: null, // 背景颜色
        dpi: 192, // 将分辨率提高到特定的dpi,默认值为96
        scale: 2, // 用于渲染的比例尺。默认为浏览器设备像素比率。默认值是1，手机端设置成2
        useCORS: true, // 是否尝试使用CORS从服务器加载图像
      }).then((canvas) => {
        this.posterUrl = canvas.toDataURL("image/jpeg");
        // downloadFileFromBlobUrl(this.posterUrl, "报告.png");
        this.$refs.img.src = this.posterUrl;
        
      });
    },
     post()
    {
        uni.postMessage({
              data: {
                  imagedata: message||'mesddddsage'
              }
          });
    },
    download()
    {
      if(!uni)
      {
        document.addEventListener('UniAppJSBridgeReady', ()=>{
          this.download(this.posterUrl)
        })
      }
      else{
          uni.postMessage({
            data: {
                imagedata: this.posterUrl||''
            }
          });

          uni.navigateBack({
            delta: 1
          });
      }
 
    }
  },
};
</script>

<style></style>
